import { Injectable } from '@nestjs/common';
import { CreateBookDto } from './dto/create-book.dto';
import { UpdateBookDto } from './dto/update-book.dto';
import { BookEntity } from './entities/book.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

@Injectable()
export class BooksService {
  // 使用InjectRepository装饰器并引入Repository这样就可以使用typeorm的操作了
  constructor(
    @InjectRepository(BookEntity)
    private readonly bookRepository: Repository<BookEntity>,
  ) {}

  create(createBookDto: CreateBookDto) {
    return 'This action adds a new book';
  }

  // 获取所有用户数据列表(userRepository.query()方法属于typeoram)
  async findAll(
    pageNum: number,
    pageSize: number,
  ): Promise<{
    code: number;
    data: BookEntity[];
    total: number;
  }> {
    const startIndex = (pageNum - 1) * pageSize;
    pageSize = typeof pageSize === 'string' ? parseInt(pageSize) : pageSize;
    const data = await this.bookRepository.query(
      'SELECT * FROM book_books LIMIT ? OFFSET ?',
      [pageSize, startIndex],
    );
    const total = data.length; // 这里假设直接返回的 data 数组长度即为总数
    const code = 200;
    return { code, data, total };
  }

  async findOne(
    bid: number,
    pageNum: number,
    pageSize: number,
  ): Promise<{ code: number; data: BookEntity[]; total: number }> {
    const startIndex = (pageNum - 1) * pageSize;
    pageSize = typeof pageSize === 'string' ? parseInt(pageSize) : pageSize;
    const data = await this.bookRepository.query(
      'SELECT * FROM book_books WHERE bookid = ? LIMIT ? OFFSET ?',
      [bid, pageSize, startIndex],
    );

    const total = data.length; // 这里假设直接返回的 data 数组长度即为总数
    const code = 200;
    return { code, data, total };
  }

  update(id: number, updateBookDto: UpdateBookDto) {
    return `This action updates a #${id} book`;
  }

  remove(id: number) {
    return `This action removes a #${id} book`;
  }
}
